package com.garbagecan.cachestudy.mycache.impl;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.jcs.JCS;
import com.garbagecan.cachestudy.mycache.CacheException;
import com.garbagecan.cachestudy.mycache.CacheManager;

public class CacheManagerJCSAdapter implements CacheManager {

	private JCS jcs;
	
	private static final String DEFAULT_REGON = "myCache";

	public CacheManagerJCSAdapter() throws CacheException {
		try {
			this.jcs = JCS.getInstance(DEFAULT_REGON);
		} catch (org.apache.jcs.access.exception.CacheException ex) {
			throw new CacheException(ex);
		}
	}

	public void put(String name, Object obj) throws CacheException {
		try {
			jcs.put(name, obj);
		} catch (org.apache.jcs.access.exception.CacheException ex) {
			throw new CacheException(ex);
		}
	}

	public void put(String group, String name, Object obj)
				throws CacheException {
		try {
			jcs.putInGroup(name, group, obj);
		} catch (org.apache.jcs.access.exception.CacheException ex) {
			throw new CacheException(ex);
		}
	}

	public void putAll(Map<String, Object> map) throws CacheException {
		for (String name : map.keySet()) {
			try {
				jcs.put(name, map.get(name));
			} catch (org.apache.jcs.access.exception.CacheException ex) {
				throw new CacheException(ex);
			}
		}
	}

	public void putAll(String group, Map<String, Object> map)
				throws CacheException {
		for (String name : map.keySet()) {
			try {
				jcs.putInGroup(name, group, map.get(name));
			} catch (org.apache.jcs.access.exception.CacheException ex) {
				throw new CacheException(ex);
			}
		}
	}

	public Object get(String name) throws CacheException {
		return jcs.get(name);
	}

	public Object get(String group, String name) throws CacheException {
		return jcs.getFromGroup(name, group);
	}

	public Map<String, Object> getAll(String group) throws CacheException {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		Set keys = jcs.getGroupKeys(group);
		for (Object key : keys) {
			map.put(key.toString(), jcs.getFromGroup(key, group));
		}
		return map;
	}

	public void remove(String name) throws CacheException {
		try {
			jcs.remove(name);
		} catch (org.apache.jcs.access.exception.CacheException ex) {
			throw new CacheException(ex);
		}
	}

	public void remove(String group, String name) throws CacheException {
		try {
			jcs.remove(name, group);
		} catch (Exception ex) {
			throw new CacheException(ex);
		}
	}

	public void removeAll(String group) throws CacheException {
		Set keys = jcs.getGroupKeys(group);
		for (Object key : keys) {
			try {
				jcs.remove(key, group);
			} catch (Exception ex) {
				throw new CacheException(ex);
			}
		}
	}

	public void clear() throws CacheException {
		try {
			jcs.clear();
		} catch (org.apache.jcs.access.exception.CacheException ex) {
			throw new CacheException(ex);
		}
	}
}
